const axios = require('axios');
const { 获取输入, 获取输入_plus, 保存图片通过base64 } = require('lidong-utils-zh');
const { saveAndOpenBase64Image } = require('lidong-utils-zh/scripts/win图片保存');
const qs = require('qs');
const sm2 = require('sm-crypto').sm2


/**
 * SM2 加密函数（一键调用）
 * @param {string} msgString - 待加密的明文字符串
 * @returns {Promise<string>} - 返回带04前缀的Hex密文
 */
const doEncrypt = async (msgString) => {
    // ----- 配置（建议通过环境变量传入）-----
    const publicKey = "C8E9B34B0482A659DCFDB2BA8DC76B99627D63EB863BE643EB52F357CE1AB309B48B41FFEEFE0C9C30C30BF5A68F1009D8E27ACDE20F668302355E3BAA0CDC22"

    const cipherMode = 1
    // ----- 核心逻辑 -----
    try {
        // 调用sm-crypto加密
        const encrypted = sm2.doEncrypt(
            msgString,
            '04' + publicKey, // 补全04前缀
            cipherMode
        );
        // 返回带04前缀的结果（与原函数一致）
        return '04' + encrypted;
    } catch (error) {
        throw new Error(`SM2加密失败: ${error.message}`);
    }
};

//userType ent.老师 per.学员
const getUserInfo = async ({
    userType,
    token
}) => {
    const url = `https://pxjg-gd.i-aq.cn/pxjgApi/yss/getUserInfo?token=${token}&userType=${userType}&sysCode=`
    let config = {
        method: 'GET',
        url,
        headers: {
            'User-Agent': 'Mozilla/5.0 (Linux; Android 13; Pixel 7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Mobile Safari/537.36',
            'Accept-Encoding': 'gzip, deflate, br, zstd',
            'Pragma': 'no-cache',
            'Cache-Control': 'no-cache',
            'sec-ch-ua-platform': '"Android"',
            'Accept-Language': 'zh-CN,zh;q=0.9',
            'sec-ch-ua': '"Google Chrome";v="141", "Not?A_Brand";v="8", "Chromium";v="141"',
            'sso-token': '',
            'project-code': 'gdpxjg',
            'sec-ch-ua-mobile': '?1',
            'token-version': 'V2.1',
            'product-code': 'pxjgApp',
            'content-type': 'application/x-www-form-urlencoded;charset=utf-8',
            'Origin': 'https://gm-gd.i-aq.cn',
            'Sec-Fetch-Site': 'same-site',
            'Sec-Fetch-Mode': 'cors',
            'Sec-Fetch-Dest': 'empty',
            'Referer': 'https://gm-gd.i-aq.cn/'
        }
    };

    const result = (await axios.request(config)).data
    return result
}

const checkIn = async ({ trId, ssoToken }) => {

    // 10签到 30签退
    let data = qs.stringify({
        'trId': trId,
        'signType': '10',
        'lon': '112.98523',
        'lat': '23.72652',
        'address': '广东省清远市清新区太和镇广东忠华纺织集团东南约119米'
    });

    let config = {
        method: 'POST',
        url: 'https://pxjg-gd.i-aq.cn/pxjgApi/student/studentTrainSign/sign',
        headers: {
            'User-Agent': 'Mozilla/5.0 (Linux; Android 12; PGT-AN00 Build/V417IR) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/83.0.4103.120 Mobile Safari/537.36',
            'Accept-Encoding': 'gzip, deflate',
            'Content-Type': 'application/x-www-form-urlencoded',
            'sso-token': ssoToken,
            'project-code': 'gdpxjg',
            'product-code': 'pxjgApp',
            'token-version': 'V2.1',
            'content-type': 'application/x-www-form-urlencoded;charset=UTF-8',
            'Origin': 'https://gm-gd.i-aq.cn',
            'X-Requested-With': 'com.android.browser',
            'Sec-Fetch-Site': 'same-site',
            'Sec-Fetch-Mode': 'cors',
            'Sec-Fetch-Dest': 'empty',
            'Referer': 'https://gm-gd.i-aq.cn/',
            'Accept-Language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7'
        },
        data: data
    };

    const result = (await axios.request(config)).data

    return result

}

const login = async ({ idToken1, idToken2, graphicVerCode, graphicVerStoreCode }) => {

    let data = JSON.stringify({
        idToken1,
        idToken2,
        "transferType": "gmv2",
        graphicVerCode,
        graphicVerStoreCode,
        "isGetChild": false
    });

    let config = {
        method: 'POST',
        url: 'https://tyrz.gd.gov.cn/pscp/sso/connect/page/auth/checkcred',
        headers: {
            'User-Agent': 'Mozilla/5.0 (Linux; Android 13; Pixel 7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Mobile Safari/537.36',
            'Accept': 'application/json, text/plain, */*',
            'Content-Type': 'application/json',
            'Pragma': 'no-cache',
            'Cache-Control': 'no-cache',
            'sec-ch-ua-platform': '"Android"',
            'Accept-Language': 'zh-CN,zh;q=0.9',
            'sec-ch-ua': '"Google Chrome";v="141", "Not?A_Brand";v="8", "Chromium";v="141"'
        },
        data: data
    };

    const result = (await axios.request(config)).data
    return result
}

const mobileloginBystore_code = async ({ store_code }) => {

    let data = JSON.stringify({
        store_code,
        "login_way": "account",
        "clientId": "tyrz_yssapp",
        "redirectUrl": "https://zwms.gdbs.gov.cn",
        "login_way_detail": "APP_SDK_PASSWORD"
    });

    let config = {
        method: 'POST',
        url: 'https://tyrz.gd.gov.cn/pscp/sso/connect/page/oauth2/mobilelogin',
        headers: {
            'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_4_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 App/com.digitalgd.dgyss/1.8.0 DGAuth/2.5.2 DGBridge/1.0.0 Language/zh-Hans-CN',
            'Accept': 'application/json, text/plain, */*',
            'Content-Type': 'application/json',
            'Content-Type': 'application/json;charset=utf-8',
            'version': '2.5.2',
            'channel': 'SG-YQT-WJSDK',
            'Sec-Fetch-Site': 'same-origin',
            'clientId': 'tyrz_yssapp',
            'Accept-Language': 'zh-CN,zh-Hans;q=0.9',
            'packagename': 'com.digitalgd.dgyss',
            'Sec-Fetch-Mode': 'cors',
            'Origin': 'https://tyrz.gd.gov.cn',
            'Sec-Fetch-Dest': 'empty',
        },
        data: data
    };

    const result = (await axios.request(config)).data
    return result
}

const yssAppLogin = async ({ grant_code }) => {
    let data = JSON.stringify({
        "grant_code": grant_code
    });

    let config = {
        method: 'POST',
        url: 'https://zwms.gdbs.gov.cn/tif/yss/app/login',
        headers: {
            'User-Agent': 'YSS/1.8.0 (iPhone; iOS 18.4.1; Scale/3.00)',
            'Content-Type': 'application/json',
            'DG-ROM': 'iOS 18.4.1',
            'DG-NetworkType': 'wifi',
            'x-tif-platform': 'app',
            'x-tif-did': 'ccbbc05b-38b1-4388-957f-4ec8b895660b',
            'DG-App-Id': 'com.digitalgd.dgyss',
            'x-tif-project': 'yss'
        },
        data: data
    };

    const result = (await axios.request(config)).data
    return result
}

const generateimagevcode = async () => {
    let config = {
        method: 'GET',
        url: 'https://tyrz.gd.gov.cn/pscp/sso/connect/page/utils/generateimagevcode?captchatype=login',
        headers: {
            'User-Agent': 'Mozilla/5.0 (Linux; Android 13; Pixel 7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Mobile Safari/537.36',
            'Accept': 'application/json, text/plain, */*',
            'Accept-Encoding': 'gzip, deflate, br, zstd',
            'Pragma': 'no-cache',
            'Cache-Control': 'no-cache',
            'sec-ch-ua-platform': '"Android"',
            'Accept-Language': 'zh-CN,zh;q=0.9',
            'sec-ch-ua': '"Google Chrome";v="141", "Not?A_Brand";v="8", "Chromium";v="141"',
            'clientId': '',
            'packagename': '',
            'sec-ch-ua-mobile': '?1',
            'channel': 'H5',
            'version': '',
            'Sec-Fetch-Site': 'same-origin',
            'Sec-Fetch-Mode': 'cors',
            'Sec-Fetch-Dest': 'empty',
            'Referer': 'https://tyrz.gd.gov.cn/pscp/sso/static/m/account-login',
        }
    };

    const result = (await axios.request(config)).data
    return result
}

const getTokeByTifSid = async ({ xTifSid }) => {

    let data = JSON.stringify({
        "bizid": "gdsyjt_sxsh_h5"
    });

    let config = {
        method: 'POST',
        url: 'https://zwms.gdbs.gov.cn/ebus/minshengwxmp/api/r/xwayapp/GetToken',
        headers: {
            'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_4_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 DGYSS/1.8.0(202505291225) DGBridge/1.2.1 Language/zh-Hans-CN',
            'Content-Type': 'application/json',
            'x-tif-sid': xTifSid,
            'x-tif-platform': 'app',
            'x-tif-project': 'yss'
        },
        data: data
    };

    const result = (await axios.request(config)).data
    return result
}

const main = async () => {

    const userType = await 获取输入_plus({
        prompt: "请输入登录类型：ent.老师 per.学员",
        key: "userType"
    })

    const account = await 获取输入_plus({
        prompt: "请输入账号：",
        key: "account"
    })
    const password = await 获取输入_plus({
        prompt: "请输入密码：",
        key: "password"
    })

    // const generateimagevcodeResult = await generateimagevcode()


    // const captchaFlag = generateimagevcodeResult.storeCode

    const captchaFlag = await 获取输入_plus({
        prompt: "请输入captchaFlag：",
        key: "captchaFlag"
    })

    // saveAndOpenBase64Image(generateimagevcodeResult.data.vcodeImageBase64)

    const captcha = await 获取输入_plus({
        prompt: "请输入验证码：",
        key: "captcha"
    })

    const loginResult = await login({
        idToken1: await doEncrypt(account),
        idToken2: await doEncrypt(password),
        graphicVerCode: captcha,
        graphicVerStoreCode: captchaFlag
    })
    console.log(loginResult);

    let storeCode = loginResult.storeCode

    const mobileloginResult = await mobileloginBystore_code({ store_code: storeCode })


    let grant_code = mobileloginResult.data.oauth2.code

    const yssAppLoginResult = await yssAppLogin({ grant_code })


    const session_id = yssAppLoginResult.data.session_id

    const tokenResult = await getTokeByTifSid({ xTifSid: session_id })

    const token = tokenResult.data.token

    const userInfoResult = await getUserInfo({ token, userType })

    const ssoToken = userInfoResult.data.ssoToken

    console.log(ssoToken);

}


main()
